// Service Worker for PWA functionality
const CACHE_NAME = 'fastapi-platform-v2';
const urlsToCache = [
  '/',
  '/manifest.json',
  '/icons/icon.svg'
];

// Install event - cache resources
self.addEventListener('install', (event) => {
  console.log('Service Worker installing...');
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then((cache) => {
        console.log('Opened cache');
        // 只缓存确实存在的资源
        return cache.addAll(urlsToCache).catch((error) => {
          console.error('Failed to cache resources:', error);
          // 即使缓存失败，也继续安装
          return Promise.resolve();
        });
      })
      .then(() => {
        console.log('Service Worker installed successfully');
        // 强制激活新的 Service Worker
        return self.skipWaiting();
      })
  );
});

// Fetch event - serve cached resources when offline
self.addEventListener('fetch', (event) => {
  // Skip caching for requests to external domains or non-GET requests
  if (!event.request.url.startsWith(self.location.origin) || event.request.method !== 'GET') {
    return;
  }

  // 对于API请求，使用网络优先策略
  if (event.request.url.includes('/api/')) {
    event.respondWith(
      fetch(event.request)
        .then((response) => {
          // 缓存成功的API响应
          if (response && response.status === 200) {
            const responseToCache = response.clone();
            caches.open(CACHE_NAME)
              .then((cache) => {
                cache.put(event.request, responseToCache);
              });
          }
          return response;
        })
        .catch(() => {
          // 网络失败时尝试从缓存获取
          return caches.match(event.request);
        })
    );
    return;
  }

  // 对于静态资源，使用缓存优先策略
  event.respondWith(
    caches.match(event.request)
      .then((response) => {
        // Return cached version or fetch from network
        if (response) {
          console.log('Returning cached response for:', event.request.url);
          return response;
        }
        
        console.log('Fetching from network:', event.request.url);
        // Clone the request because request streams can only be consumed once
        const fetchRequest = event.request.clone();
        
        return fetch(fetchRequest)
          .then((response) => {
            // Check if we received a valid response
            if (!response || response.status !== 200 || response.type !== 'basic') {
              console.log('Network response not cacheable:', response ? response.status : 'no response');
              return response;
            }
            
            // Clone the response because response streams can only be consumed once
            const responseToCache = response.clone();
            
            // Cache the response for future use
            caches.open(CACHE_NAME)
              .then((cache) => {
                console.log('Caching response for:', event.request.url);
                cache.put(event.request, responseToCache);
              })
              .catch((error) => {
                console.error('Failed to cache response:', error);
              });
              
            return response;
          })
          .catch((error) => {
            console.error('Network fetch failed for:', event.request.url, error);
            // Re-throw the error to maintain the original behavior
            throw error;
          });
      })
      .catch((error) => {
        console.error('Cache match failed for:', event.request.url, error);
        // Try to fetch from network as a fallback
        return fetch(event.request).catch((networkError) => {
          console.error('Network fetch also failed for:', event.request.url, networkError);
          // If both cache and network fail, you might want to return a fallback page
          throw networkError;
        });
      })
  );
});

// Activate event - clean up old caches
self.addEventListener('activate', (event) => {
  console.log('Service Worker activating...');
  event.waitUntil(
    caches.keys().then((cacheNames) => {
      return Promise.all(
        cacheNames.map((cacheName) => {
          if (cacheName !== CACHE_NAME) {
            console.log('Deleting old cache:', cacheName);
            return caches.delete(cacheName);
          }
        })
      );
    })
    .then(() => {
      console.log('Service Worker activated successfully');
      // 立即控制所有客户端
      return self.clients.claim();
    })
  );
});

// Push notification handling
self.addEventListener('push', (event) => {
  const options = {
    body: event.data ? event.data.text() : 'New notification',
    icon: '/icons/icon.svg',
    vibrate: [100, 50, 100],
    data: {
      dateOfArrival: Date.now(),
      primaryKey: 1
    }
  };

  event.waitUntil(
    self.registration.showNotification('FastAPI Platform', options)
  );
});

// Notification click handling
self.addEventListener('notificationclick', (event) => {
  console.log('Notification click received.');

  event.notification.close();

  if (event.action === 'explore') {
    // Open the app
    event.waitUntil(
      clients.openWindow('/')
    );
  } else if (event.action === 'close') {
    // Just close the notification
    console.log('Notification closed by user action');
  } else {
    // Default action - open the app
    event.waitUntil(
      clients.openWindow('/')
    );
  }
});

// Background sync
self.addEventListener('sync', (event) => {
  if (event.tag === 'background-sync') {
    event.waitUntil(doBackgroundSync());
  }
});

async function doBackgroundSync() {
  // Implement background sync logic here
  console.log('Background sync triggered');
}